// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "gitreader" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('gitreader.gitreader', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		let uri = vscode.Uri.file("D:\\code\\git\\git");
		readMetadta().then(metadata => {
			documentFuncs(metadata);
		});


		// let filePath = "D:\\code\\git\\git\\scripts\\data\\files_data.json";
		// openLocalFile(filePath);		

		vscode.window.showInformationMessage('Hello World from gitreader!');
	});

	context.subscriptions.push(disposable);
}

async function readMetadta() {
	let filePath = "D:\\code\\git\\git\\scripts\\data\\files_data.json";
	let doc = await vscode.workspace.openTextDocument(filePath);
	let text = doc.getText();
	let metadata = JSON.parse(text);
	return metadata;
}

async function documentFuncs(metadata: any) {
	for (let fileItem of metadata.files) {
		if (fileItem.function_list.length === 0 || fileItem.function_list[0].document === "done") {
			continue;
		}
		if (fileItem.filename.startsWith("t\\")) {
			continue;
		}

		let filepath = "D:\\code\\git\\git\\" + fileItem.filename;
		let doc = await vscode.workspace.openTextDocument(filepath);
		await vscode.window.showTextDocument(doc);

		for (let index = fileItem.function_list.length - 1; index >= 0; index--) {
			let func = fileItem.function_list[index];
			if (func.document === "done") {
				continue;
			}

			let selector = new vscode.Selection(func.star_line, 0, func.star_line + 1, 0);
			if (doc.getText(selector).indexOf(func.line) < 0) {
				func.document = "skip";
				continue;
			}
			if (vscode.window.activeTextEditor) {
				vscode.window.activeTextEditor.selection = selector;
			} else {
				await vscode.window.showTextDocument(doc, { selection: selector, viewColumn: 1, preview: false });
			}

			let res1 = await vscode.commands.executeCommand("cody.command.document-code");
			for (let i = 0; i < 40; i++) {
				await delay(3);
				let selector = new vscode.Selection(func.star_line, 0, func.star_line + 1, 0);
				let text = doc.getText(selector);
				if (text.endsWith("/**\n") || text.endsWith("/*\n") || text.startsWith("/* ")) {
					break;
				}
			}

			let sel = new vscode.Selection(func.star_line, 0, func.star_line + 1, 0);
			if (doc.getText(sel).indexOf(func.line) >= 0) {
				return;
			}

			let res2 = await vscode.commands.executeCommand("workbench.action.files.save");
			func.document = "done";
			await saveMetadata(JSON.stringify(metadata, null, "\t"));
		}
		await vscode.commands.executeCommand("workbench.action.files.save");
		await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
	}
}

async function saveMetadata(content: string) {
	let filePath = "D:\\code\\git\\git\\scripts\\data\\files_data.json";
	let uri = vscode.Uri.file(filePath);
	await vscode.workspace.fs.writeFile(uri, Buffer.from(content));
}

function delay(seconds: number) {
	return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}

// This method is called when your extension is deactivated
export function deactivate() { }
